var express = require('express')
var app = express(), http = require('http'), path = require('path');
var mongodb = require('mongodb');
var config = require('./config.js');
var parser = require('ua-parser-js');
//var QR = require('./BaeImageQRCode.js');
/*
try{
    var pinyin = require('pinyin');
}catch(e){
    console.log('pinyin module not found!');
}
*/

//var favicon = require('serve-favicon');
var logger = require('morgan');
var methodOverride = require('method-override');
var session = require('express-session');
var bodyParser = require('body-parser');
var multer = require('multer');
var errorHandler = require('errorhandler');


var MongoClient = mongodb.MongoClient;
var db;
var Wen = require('wenurl');
var wen = new Wen();

// all environments
app.set('port', 18080);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(methodOverride());
app.use(session({ resave: true,
    saveUninitialized: true,
    secret: 'uwotm8' }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer());

/*app.set('port', 18080);
app.set('views', __dirname + '/views');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('expressdemo'));
app.use(express.session());
app.use(app.router);
app.use(express.errorHandler());*/

app.use(express.static(path.join(__dirname, 'assets')));
// development only
if ('development' == app.get('env')) {
    app.use(errorHandler());
}
app.get('/', function(req, res){
    res.render('index.ejs', {
        title: '短网址 短网址接口 短网址API 生成短网址',
        host: req.header('host')
    });
});

app.get('/([a-zA-Z0-9]{6})', function(req, res){
    req.params.code = req.url.substr(1,6);
    wen.getHandler(req, res);
});

app.get('/short_url.:format', addHandler);
app.get('/api/add', addHandler);
app.get('/ShortApi/Add', addHandler);

app.get('/monitor/:code', function (req, res) {
    var code = req.params.code;
    var vitis = db.collection('vitis');
    vitis.find({key: code}, {sort: {_id:-1}}, function (err, cursor) {
        if(err){
            //throw 'not found key.';
            res.send(err.message);
            return;
        }

        cursor.toArray(function (err, r) {
            res.render('monitor.ejs', {
                rows: r,
                parser: parser
            });
        });
    });
});

app.get('/monitor', function (req, res) {
    var vitis = db.collection('vitis');
    var date = new Date();
    var today = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0).getTime();
    var limit = req.query.limit || 100;
    vitis.count(function (err, total) {
        vitis.find({time: {$gt: today}}).count(function (err, todayCount) {
            if(err){
                console.log('todayCount err: ',err);
                return;
            }
            vitis.find({time: {$gt: today}}, {sort: {_id:-1}, limit: limit}, function (err, cursor) {
                if(err){
                    res.send(err.message);
                    return;
                }
                cursor.toArray(function (err, r) {
                    res.render('monitor.ejs', {
                        rows: r,
                        parser: parser,
                        total: total,
                        todayCount: todayCount
                    });
                });
            })
        });

    });
});

//app.get('/api/qrcode', QR.QRCode);
/*app.get('/api/pinyin/:style', zh2py);
app.get('/api/pinyin', zh2py);

function zh2py(req, res){
    var word = req.param('word') || '';
    var style = req.params['style'] || 'B';
    var delimiter = req.param('delimiter')||'';
    var styles = {
        'A':0,'B':1,'C':2,'D':3,'E':4
    };
    if(!word && !word.length){
        res.send({error: "Parameter 'word' can not be empty", code: 1001});
    }else{
        var py = pinyin(word,{
            style: parseInt(styles[style.toUpperCase()])
        });
        if(delimiter){
            py = py.join(delimiter);
        }else{
            py = py.join('\0').split('\0');
        }
        res.send({pinyin: py});
    }
}*/

function addHandler(req, res){
    req.query.dataType = req.params.format||'json';
    req.query.jsonpCallback = req.query.jsonpCallback || 'www_50r_cn_jsonp_callback';
    wen.addHandler(req, res);
}

// Initialize connection once
var dsn = "mongodb://" + config.mongodb.host + ":" + config.mongodb.port + "/" + config.mongodb.name;

MongoClient.connect(dsn, function(err, database) {
    if(err) throw err;

    db = database;

    wen.db = database;
    wen.config = config;

    // Start the application after the database connection is ready
    app.listen(18080);
    console.log("Listening on port 18080");
});

/*
app.get('/import/mysql', function(req,res){
    var fs = require('fs');
    var filename = req.query.file;
    var ShortURL = require('./ShortURL');
    fs.readFile('./data/' + filename, function(err, data){
        if(err || !data || !data.length){
            res.end(err.message);
            return;
        }
        var d = data.toString().split("\n");
        //var l = [];
        var short = new ShortURL(req, res);
        short.open(function(){
            short.getCollection(function(collection){
                if(collection){
                    for(var i=0;i< d.length;i++){
                        var line = d[i];
                        if(/\(\d+[\s,]+'.*?'[\s,]+'.*?'[\s,]+'.*?'\),/.test(line)){
                            var m = line.match(/\(\d+[\s,]+'(.*?)'[\s,]+'(.*?)'[\s,]+'(.*?)'\),/);
                            var surl = {
                                key: m[1],
                                userId:0,
                                url: m[2],
                                addTime: new Date(m[3])
                            };
                            collection.insert(surl,{safe: true},function(err,res){
                                //l.push(surl)
                                //console.log(l.length)
                            });
                        }
                    }
                    res.send('ok')
                }else{
                    res.send('not found collection')
                }
            });
        });
    });
});
*/
